package com.nanrui.mutualinductor.ui.page;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

import com.batman.baselibrary.base.BaseActivity;
import com.batman.baselibrary.utils.ToastUtils;

import java.io.IOException;
import java.util.UUID;

public abstract class MyBlueActivity extends BaseActivity {

    private final int REQUEST_ENABLE_BT = 998;
    protected BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBluetoothReceiver);
    }

    @Override
    public void loadData(Bundle savedInstanceState) {

        // 注册用以接收到已搜索到的蓝牙设备的receiver
        IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBluetoothReceiver, mFilter);
        // 注册搜索完时的receiver
        mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mBluetoothReceiver, mFilter);
    }

    protected void scan() {
        //蓝牙初始化,获取BluetoothAdapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {

            if (mBluetoothAdapter.isEnabled()) {
                startDiscovery();
            } else {
                //蓝牙权限被禁止，请在权限管理中打开
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
            //若没打开则打开蓝牙
//            boolean isEnable = mBluetoothAdapter.enable();

        } else {
            ToastUtils.showLong("您的设备不支持蓝牙");
        }
    }

    private void startDiscovery() {
        //当前是否在扫描，如果是就取消当前的扫描，重新扫描
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        if (mBluetoothAdapter != null && mBluetoothAdapter.startDiscovery()) {
            //启动蓝牙扫描附近设备
        } else {
            //蓝牙扫描失败
        }
    }

    // 广播接收发现蓝牙设备
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //发现蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                Log.d("scanResultListMacAdress",
                        device.getAddress());

                Log.d("scanResultListMacName",
                        device.getName());

                //开启线程进行蓝牙连接
                new Thread(new ConnectThread(mSelectBluetooth)).start();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //蓝牙搜索完成
                // 蓝牙搜索是非常消耗系统资源开销的过程，搜索完毕后应该及时取消搜索
                mBluetoothAdapter.cancelDiscovery();
            }
        }
    };


    private BluetoothDevice mSelectBluetooth;
    private BluetoothSocket socket = null;
    private final String BLUETOOTH_UUID = "00001101-0000-1000-8000-00805F9B34FB";   //蓝牙通信的UUID，必须为这个，如果换成其他的UUID会无法通信

    /**
     * 接收数据
     */

    private static final String NAME = "BluetoothChat";

    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            // Use a temporary object that is later assigned to mmServerSocket
            // because mmServerSocket is final.
            BluetoothServerSocket tmp = null;
            try {
                // MY_UUID is the app's UUID string, also used by the client code.
                tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, UUID.fromString(BLUETOOTH_UUID));
            } catch (IOException e) {
                Log.e(TAG, "Socket's listen() method failed", e);
            }
            mmServerSocket = tmp;
        }

        @Override
        public void run() {
            BluetoothSocket socket = null;
            // Keep listening until exception occurs or a socket is returned.
            while (true) {
                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "Socket's accept() method failed", e);
                    break;
                }

                if (socket != null) {
                    // A connection was accepted. Perform work associated with
                    // the connection in a separate thread.
                    manageMyConnectedSocket(socket);
                    try {
                        mmServerSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        // Closes the connect socket and causes the thread to finish.
        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close the connect socket", e);
            }
        }
    }


    /**
     * 发送数据
     */

    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket
            // because mmSocket is final.
            BluetoothSocket tmp = null;
            mmDevice = device;

            try {
                // Get a BluetoothSocket to connect with the given BluetoothDevice.
                // MY_UUID is the app's UUID string, also used in the server code.
                tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(BLUETOOTH_UUID));
            } catch (IOException e) {
                Log.e(TAG, "Socket's create() method failed", e);
            }
            mmSocket = tmp;
        }

        @Override
        public void run() {
            // Cancel discovery because it otherwise slows down the connection.
            mBluetoothAdapter.cancelDiscovery();

            try {
                // Connect to the remote device through the socket. This call blocks
                // until it succeeds or throws an exception.
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and return.
                try {
                    mmSocket.close();
                } catch (IOException closeException) {
                    Log.e(TAG, "Could not close the client socket", closeException);
                }
                return;
            }

            // The connection attempt succeeded. Perform work associated with
            // the connection in a separate thread.
            manageMyConnectedSocket(mmSocket);
        }

        // Closes the client socket and causes the thread to finish.
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close the client socket", e);
            }
        }
    }

    protected void manageMyConnectedSocket(BluetoothSocket mmSocket) {

    }


    /**
     * 发送数据
     *
     * @param data  要发送的数据 字符串
     * @param isHex 是否是16进制字符串
     * @return true 发送成功  false 发送失败
     */
//    public boolean sendData(String data, boolean isHex) {
//        if (data == null || data.length() == 0) {
//            Log.e(TAG, "sendData:string-->要发送的数据为空");
//            return false;
//        }
//
//        if (isHex) {  //是16进制字符串
//            data.replace(" ", "");  //取消空格
//            //检查16进制数据是否合法
//            if (data.length() % 2 != 0) {
//                //不合法，最后一位自动填充0
//                String lasts = "0" + data.charAt(data.length() - 1);
//                data = data.substring(0, data.length() - 2) + lasts;
//            }
//            Log.d(TAG, "sendData:string -->准备写入：" + data);  //加空格显示
//            return connectedThread.write(hexString2Bytes(data));
//        }
//
//        //普通字符串
//        Log.d(TAG, "sendData:string -->准备写入：" + data);
//        return connectedThread.write(data.getBytes());
//    }


//    /**
//     * 蓝牙连接的线程
//     */
//    private class ClientThread extends Thread {
//
//        private BluetoothDevice device;
//
//        public ClientThread(BluetoothDevice device) {
//            this.device = device;
//        }
//
//        @Override
//        public void run() {
//
//
//            try {
//                socket = device.createRfcommSocketToServiceRecord(UUID.fromString(BLUETOOTH_UUID));
//
//                Log.d(TAG, "连接服务端...");
//                socket.connect();
//
//                Log.d(TAG, "连接建立.");
//
//                ReadThread readThread = new ReadThread();  //连接成功后开启读取该蓝牙设备数据的线程
//                readThread.start();
//            } catch (Exception e) {
//                //连接已断开
//            }
//        }
//    }

    //连接设备和读取数据都需要新启线程在子线程中进行，因为过程比较耗时，如果不在子线程影响效率和阻塞UI。代码我就不做解释了，上面注释写的很清楚了。下面贴读取数据的操作：
    //读写线程
//    private class ReadThread extends Thread {
//        @Override
//        public void run() {
//            byte[] buffer = new byte[1024];
//            int bytes;
//            InputStream mmInStream = null;   //建立输入流读取数据
//            try {
//                mmInStream = socket.getInputStream();
//            } catch (IOException e1) {
//                // TODO Auto-generated catch block
//                e1.printStackTrace();
//            }
//            while (true) {  //无限循环读取数据
//                try {
//                    // Read from the InputStream
//                    if ((bytes = mmInStream.read(buffer)) > 0) {
//                        byte[] buf_data = new byte[bytes];
//                        for (int i = 0; i < bytes; i++) {
//                            buf_data[i] = buffer[i];
//                        }
//
//                        //String s = bytesToHexString(buf_data);
//                        System.arraycopy(buffer, 0, buf_data, 0, bytes);
//                        final int finalBytes = bytes;
//
////                        final String text = TemperatureUtil.getHexString(buf_data, 0, finalBytes);
////
////                        Log.d(TAG, "读取到的温度为: " + TemperatureUtil.getResultTemperature(text));
//
//                    }
//                } catch (Exception e) {
//                    try {
//                        mmInStream.close();
//                    } catch (IOException e1) {
//
//                    }
//
//                    break;  //异常的时候break跳出无限循环
//                }
//            }
//        }
//    }
}
